package com.yan.learn.controller;

import com.yan.learn.utils.OperationFileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author: WangYanjing
 * @Date: 2019/6/5 18:27
 * @Description:
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {

    @Value("${breakpoint.download.dir}")
    private String filePath;

    @RequestMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "failure";
        } else {
            String filename = file.getOriginalFilename();
            // 将文件保存到一个目标文件中
            file.transferTo(new File(filePath + File.separator + filename));
            return "success";
        }

    }

    @RequestMapping(value = "/download")
    @ResponseBody
    public Object download(@RequestParam("fileName") String fileName) throws IOException {
        OperationFileUtil.download(filePath + fileName, fileName);
        return null;
    }
}